/**
 * Created by seikann on 2017-10-10.
 */
const models = require('../mongoDB/db');
const express = require('express');
const router = express.Router();

/************** 创建(create) 读取(get) 更新(update) 删除(delete) **************/

// 创建账号接口
router.post('/api/login/createAccount', (req, res) => {
  // 这里的req.body能够使用就在index.js中引入了const bodyParser = require('body-parser')
  if (req.session.user) {
    let newAccount = new models.Login({
      userName: req.body.userName,
      password: req.body.password
    });
    // 保存数据newAccount数据进mongoDB
    let criteria = {userName: req.body.userName};
    models.Login.find(criteria, (err, data) => {
      if (err) {
        res.send(err);
      } else {
        if (data.length == 0 && req.body.userName != "") {
          newAccount.save((err, data) => {
            if (err) {
              res.send(err);
            } else {
              res.send({
                message: "操作成功",
                code: "0"
              });
            }
          });
        } else {
          res.send({
            message: "账号已存在或账号密码不能为空",
            code: "-1"
          });
        }

      }
    });
  } else {
    res.send({
      message: "请登录",
      code: "1"
    });

  }

});
// 更新指定账号接口
router.post('/api/login/updateAccount', (req, res) => {
  // 通过模型去查找数据库
  if (req.session.user) {
    let conditions = {userName: req.body.userName};
    let updates = {$set: {password: req.body.newPassword}};
    let options = {upsert: true};
    if (Boolean(conditions.userName)) {
      models.Login.update(conditions, updates, options, (err, data) => {
        if (err) {
          res.send(err);
        } else {
          res.send({
            message: "保存成功",
            code: "0"
          });
        }
      });
    } else {
      res.send({
        message: "目标账号不存在",
        code: "-1"
      });
    }
  } else {
    res.send({
      message: "请登录",
      code: "1"
    });

  }
});
// 查询所有已有账号接口
router.get('/api/login/getAccount', (req, res) => {
  if (req.session.user) {
// 通过模型去查找数据库
    models.Login.find((err, data) => {
      if (err) {
        res.send(err);
      } else {
        let dataNew = {
          message: "操作成功",
          code: '0',
          data: ''
        };
        dataNew.data = data;
        res.send(dataNew);
      }
    });
  } else {
    res.send({
      message: "请登录",
      code: "1"
    });

  }

});
// 删除已有账号接口
router.post('/api/login/deleteAccount', (req, res) => {
  // 通过模型去查找数据库
  if (req.session.user) {
    let conditions = {userName: req.body.userName};
    models.Login.remove(conditions, (err, data) => {
      if (err) {
        res.send(err);
      } else {
        res.send({
          message: "删除成功",
          code: "0"
        });
      }
    });
  } else {
    res.send({
      message: "请登录",
      code: "1"
    });

  }
});

module.exports = router;
